package com.ruoyi.api.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.api.service.SelectAuditService;
import com.ruoyi.audit.domain.AmountDetailed;
import com.ruoyi.audit.domain.Audit;
import com.ruoyi.audit.domain.InventoryAmount;
import com.ruoyi.audit.service.AuditService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.WXShiroUtils;
import com.ruoyi.monthlyInventory.domain.MonthlyInventory;
import com.ruoyi.monthlyInventory.domain.MonthlyInventoryLog;
import com.ruoyi.monthlyInventory.service.MonthlyInventoryService;
import com.ruoyi.procurement.domain.ProcurementOrder;
import com.ruoyi.procurement.service.ProcurementServer;
import com.ruoyi.product.domain.Product;
import com.ruoyi.product.domain.ProductModel;
import com.ruoyi.purchase.domain.PurchaseModel;
import com.ruoyi.purchase.domain.PurchaseOrder;
import com.ruoyi.purchase.service.PurchaseOrderService;
import com.ruoyi.purchaseReturn.domain.PurchaseReturnOrder;
import com.ruoyi.purchaseReturn.service.IPurchaseReturnService;
import com.ruoyi.sale.domain.SaleGoodsModel;
import com.ruoyi.sale.domain.SaleGoodsOrder;
import com.ruoyi.sale.domain.SaleorderModel;
import com.ruoyi.sale.domain.SaleorderOrder;
import com.ruoyi.sale.service.ISaleGoodsService;
import com.ruoyi.sale.service.ISaleorderService;
import com.ruoyi.saleReturn.domain.SaleReturnModel;
import com.ruoyi.saleReturn.domain.SaleReturnOrder;
import com.ruoyi.saleReturn.service.ISaleReturnService;
import com.ruoyi.salesInvoice.domain.SalesInvoiceOrder;
import com.ruoyi.salesInvoice.service.SalesInvoiceService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.warehousing.service.WarehousingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * wx 审核订单管理
 */
@Controller
@RequestMapping("/wx/business/selectAudit")
public class SelectAuditController extends BaseController {
    @Autowired
    private SelectAuditService selectAuditService;

    @Autowired
    private AuditService auditService;

    @Autowired
    private PurchaseOrderService purchaseOrderService;

    @Autowired
    private ISaleorderService iSaleorderService;

    @Autowired
    private ProcurementServer procurementServer;

    @Autowired
    private ISaleGoodsService iSaleGoodsService;

    @Autowired
    private SalesInvoiceService salesInvoiceService;

    @Autowired
    private WarehousingService warehousingService;

    @Autowired
    private MonthlyInventoryService monthlyInventoryService;

    @Autowired
    private IPurchaseReturnService iPurchaseReturnService;

    @Autowired
    private ISaleReturnService iSaleReturnService;

    @Autowired
    private ISysRoleService roleService;

    /**
     * 查询订单审核列表
     */
    @PostMapping("/auditList")
    @ResponseBody
    public TableDataInfo list(Audit audit) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Long companyId = sysUser.getCompanyId();
        audit.setCompanyId(companyId);
        List<Audit> list = new ArrayList<>();
        Long userId = sysUser.getUserId();
        List<SysRole> list1 = roleService.selectRolesByUserIds(userId);
        startPage();
        if (list1.size() != 0) {
            for (SysRole sysRole : list1) {
                if (sysRole.getRoleId() == 2) {
                    return getDataTable(selectAuditService.selectAuditList(audit));
                } else if (sysRole.getRoleId() == 105) {
                    return getDataTable(auditService.selectAuditLists(audit));
                }
//                if (sysRole.getRoleId() == 2 && sysRole.isFlag()) {
//                    return getDataTable(selectAuditService.selectAuditList(audit));
//                } else if (sysRole.getRoleId() == 105 && sysRole.isFlag()) {
//                    return getDataTable(auditService.selectAuditLists(audit));
//                }
            }
        }

//        list = auditService.selectAuditLists(audit);
//        list = selectAuditService.selectAuditList(audit);
//        return getDataTable(list);
        return getDataTable(list);
    }

    /**
     * 查询订单审核详情
     */
    @PostMapping("/audit")
    @ResponseBody
    public AjaxResult list(Long auditId) {
        Map<Object, Object> map = new HashMap<>();
        Audit audit = auditService.selectAuditById(auditId);
        Long companyId = WXShiroUtils.getSysUser().getCompanyId();
        map.put("auditId", auditId);
        map.put("auditStatus", audit.getAuditStatus());
        map.put("auditRemark", audit.getAuditRemark());
        String type = audit.getOrderType();
        if ("1".equals(type)) {
            Long purchaseId = audit.getOrderId();
            PurchaseOrder purchaseOrder = purchaseOrderService.selectPurchaseOrderById(purchaseId);
            List<PurchaseModel> purchaseModels = purchaseOrderService.selectPurchaseModelById(purchaseId);
            map.put("purchaseOrder", purchaseOrder);
            map.put("purchaseModels", purchaseModels);
            return AjaxResult.success(map);
        } else if ("2".equals(type)) {
            ProcurementOrder procurementOrders = new ProcurementOrder();
            procurementOrders.setProcurementWarehousingId(audit.getOrderId());
            ProcurementOrder procurementOrder1 = procurementServer.selectProcurementBy(procurementOrders);
            List<Product> procurementModel = procurementServer.selectProcurementByIds(procurementOrder1.getProcurementWarehousingId());
            procurementOrder1.setProducts(procurementModel);
            map.put("procurementOrder", procurementOrder1);
            return AjaxResult.success(map);
        } else if ("0".equals(type)) {
            Long saleorderId = audit.getOrderId();
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("saleorderId", saleorderId);
            hashMap.put("deptId", companyId);
            SaleorderOrder saleorderOrder = iSaleorderService.selectSaleorderById(hashMap);
            List<Product> products = iSaleorderService.selectSaleOrderModelById(saleorderId);
            saleorderOrder.setProducts(products);
            map.put("saleorderOrder", saleorderOrder);
            return AjaxResult.success(map);
        } else if ("4".equals(type)) {
            MonthlyInventoryLog monthlyInventoryLog = monthlyInventoryService.selectMonthlyInventoryLogById(audit.getOrderId());
            MonthlyInventory monthlyInventory = monthlyInventoryService.selectMonthlyInventoryById(monthlyInventoryLog.getMonthlyInventoryId());
            map.put("monthlyInventory", monthlyInventory);
            map.put("num", monthlyInventoryLog.getChangeNum());
            return AjaxResult.success(map);
        } else if ("5".equals(type)) {
            PurchaseReturnOrder purchaseReturnOrder = iPurchaseReturnService.selectPurchaseReturnById(audit.getOrderId());
            map.put("purchaseReturnOrder", purchaseReturnOrder);
            return AjaxResult.success(map);
        } else if ("6".equals(type)) {
            SaleReturnOrder saleReturnOrder = iSaleReturnService.selectSaleReturnOrderAndModelById(audit.getOrderId());
            if (saleReturnOrder.getSaleReturnModels().get(0).getSaleReturnId() == null) {
                List<SaleReturnModel> list = new ArrayList();
                saleReturnOrder.setSaleReturnModels(list);
                map.put("saleReturnOrder", saleReturnOrder);
            } else {
                //查询 采购入库单的信息 set进model 中
                if (saleReturnOrder.getPurchaseReturnId() != null) {
                    List<Product> products = iPurchaseReturnService.selectPurchaseReturnModelByNo(saleReturnOrder.getPurchaseReturnId());
                    saleReturnOrder.setProducts(products);
                } else {
                    List<Product> products = iSaleGoodsService.selectSaleGoodsModelByNo(saleReturnOrder.getSaleGoodsId());
                    saleReturnOrder.setProducts(products);
                }
                map.put("saleReturnOrder", saleReturnOrder);
            }
            return AjaxResult.success(map);
        } else if ("7".equals(type)) {
            SalesInvoiceOrder salesInvoiceOrder = salesInvoiceService.selectSalesInvoiceOrderById(audit.getOrderId());
            map.put("salesInvoiceOrder", salesInvoiceOrder);
            System.out.println(AjaxResult.success(map));
            return AjaxResult.success(map);
        } else {
            Long saleGoodsId = audit.getOrderId();
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("saleGoodsId", saleGoodsId);

            SaleGoodsOrder saleGoodsOrder = iSaleGoodsService.selectSaleGoodsById(hashMap);
            //判断子集是否存在
            if (saleGoodsOrder.getSaleGoodsModels().get(0).getSaleGoodsModelId() == null) {
                //没有的话 给个空的集合
                List<SaleGoodsModel> list = new ArrayList();
                saleGoodsOrder.setSaleGoodsModels(list);
                map.put("saleGoodsOrder", saleGoodsOrder);
            } else {
                map.put("saleGoodsOrder", saleGoodsOrder);
            }
            return AjaxResult.success(map);
        }
    }

    public JSONArray selectProduct(Long deptId) {
        List<Product> productList = purchaseOrderService.selectProduct(deptId);
        JSONArray array = new JSONArray();
        for (Product product : productList) {
            if (product.getProductModel().size() != 0) {
                List<ProductModel> productModels = product.getProductModel();
                for (ProductModel productModel : productModels) {
                    JSONObject obj = new JSONObject();
                    obj.put("productId", product.getProductId());
                    obj.put("productName", product.getProductName());
                    obj.put("modelNo", productModel.getModelNo());
                    obj.put("modelCode", productModel.getModelCode());
                    obj.put("productType", productModel.getProductType());
                    obj.put("warehousingNum", productModel.getWarehousingNum());
                    obj.put("salesUnit", productModel.getSalesUnit());
                    array.add(obj);
                }
            }
        }
        return array;
    }

    /**
     * 修改保存订单审核
     */
    @Log(title = "订单审核", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Audit audit) throws Exception {
//        return AjaxResult.error("错误提示");
        Audit audit1 = auditService.selectAuditByIdIn(audit.getAuditId());
        if (audit1.getAuditStatus().equals("1") || audit1.getAuditStatus().equals("2")) {
            audit.setAuditStatus(audit1.getAuditStatus());
            return AjaxResult.error("该订单已经审核完成");
        }
        if (audit.getAuditStatus() != null && !audit.getAuditStatus().equals("")) {
            audit1.setAuditBy(WXShiroUtils.getSysUser().getUserName());
            audit1.setAuditTime(DateUtils.getNowDate());
        }
        if (audit.getAuditStatus() != null && !audit.getAuditStatus().equals("")) {
            audit.setAuditBy(WXShiroUtils.getSysUser().getUserName());
            audit.setAuditTime(DateUtils.getNowDate());
        }
        Long deptId = WXShiroUtils.getCompanyId();
        int i = auditService.updateAudit(audit, deptId);

        AmountDetailed amountDetailed = new AmountDetailed();
        InventoryAmount inventoryAmount = new InventoryAmount();

        if ("2".equals(audit1.getOrderType()) && i == 1) {
            ProcurementOrder procurementOrder = new ProcurementOrder();
            procurementOrder.setProcurementWarehousingId(audit1.getOrderId());
            if (audit.getAuditStatus().equals("1")) {
                procurementServer.calculation(procurementOrder);
                inventoryAmount.setDeptId(WXShiroUtils.getSysUser().getCompanyId());
                inventoryAmount.setOrderType("0");
                inventoryAmount.setOrderId(audit1.getOrderId());
                inventoryAmount.setAuditId(audit1.getAuditId());
                auditService.insertInventoryAmount(inventoryAmount);
            }
        } else if ("3".equals(audit1.getOrderType())) {
            SaleGoodsOrder saleGoodsOrder = new SaleGoodsOrder();
            saleGoodsOrder.setSaleGoodsId(audit1.getOrderId());
            saleGoodsOrder.setSaleGoodsStatus(audit.getAuditStatus());
            if (audit.getAuditStatus().equals("1")) {
                iSaleGoodsService.outboundAudit(saleGoodsOrder);

                inventoryAmount.setDeptId(WXShiroUtils.getSysUser().getCompanyId());
                inventoryAmount.setOrderType("1");
                inventoryAmount.setOrderId(audit1.getOrderId());
                inventoryAmount.setAuditId(audit1.getAuditId());
                auditService.updateInventoryAmount(inventoryAmount);
            } else {
                iSaleGoodsService.auditSalesOrderEdit(audit1.getOrderId());
            }
            //如果拒绝则 将选中的销售订单 修改
            //根据主键查询数据，判断是否含有产品规格型号子集
            HashMap hashMap = new HashMap();
            hashMap.put("saleGoodsId", audit1.getOrderId());
            SaleGoodsOrder saleGoodsOrder1 = iSaleGoodsService.selectSaleGoodsById(hashMap);
            SaleorderOrder saleorderOrder = new SaleorderOrder();
            Long saleorderId = saleGoodsOrder1.getSaleorderId();
            saleorderOrder.setSaleorderId(saleorderId);
            saleorderOrder.setIsCreateGoods("0");
            iSaleorderService.updateSaleorder(saleorderOrder);
        } else if ("4".equals(audit1.getOrderType())) {
            MonthlyInventoryLog monthlyInventoryLog = new MonthlyInventoryLog();
            monthlyInventoryLog.setLogId(audit1.getOrderId());
            warehousingService.calculation(monthlyInventoryLog);
        } else if ("5".equals(audit1.getOrderType())) {
            PurchaseReturnOrder purchaseReturnOrder = new PurchaseReturnOrder();
            purchaseReturnOrder.setPurchaseReturnId(audit1.getOrderId());
            purchaseReturnOrder.setPurchaseReturnStatus(audit.getAuditStatus());
            iPurchaseReturnService.returnAudit(purchaseReturnOrder);
        } else if ("6".equals(audit1.getOrderType())) {
            Long saleReturnId = audit1.getOrderId();
            String status = audit.getAuditStatus();
            iSaleReturnService.saleReturnAudit(saleReturnId, status);
        } else if ("7".equals(audit1.getOrderType())) {
            Long salesInvoiceId = audit1.getOrderId();
            String status = audit.getAuditStatus();
            if (status.equals("2")) {
                salesInvoiceService.countReturnSalesGoods(salesInvoiceId);
            } else {
                salesInvoiceService.countIsInvoice(salesInvoiceId);
            }
        }
        return toAjax(i);
    }

    /**
     * 查询订单审核列表
     */
    @PostMapping("/auditLists")
    @ResponseBody
//    public Map<String, Object> lists() {
    public AjaxResult lists() {
        Map<String, Object> map = new HashMap<>();
        Long companyId = WXShiroUtils.getSysUser().getCompanyId();
        SaleorderOrder saleorderOrder = new SaleorderOrder();
        saleorderOrder.setDeptId(companyId);
        if (!WXShiroUtils.getSysUser().getDeptId().equals(WXShiroUtils.getSysUser().getCompanyId())) {
            saleorderOrder.setUserId(WXShiroUtils.getUserId());
        }
        List<SaleorderOrder> list = iSaleorderService.selectSaleorderCustObj(saleorderOrder);
        return AjaxResult.success(list);
    }

    /**
     * 查询销售订单详情
     */
    @PostMapping("/selectSaleorders")
    @ResponseBody
//    public Map<String, Object> lists() {
    public AjaxResult selectSaleorders(SaleorderOrder saleorderOrder) {
        Map<String, Object> map = new HashMap<>();
        Long companyId = WXShiroUtils.getSysUser().getCompanyId();
        saleorderOrder.setDeptId(companyId);
        saleorderOrder.setIsCreateGoods("1");

        List<SaleorderOrder> saleorderOrderList = new ArrayList<SaleorderOrder>();
        List<SaleorderModel> saleorderModelList = new ArrayList<SaleorderModel>();

        if (saleorderOrder.getCompanyId() == null) {
            map.put("saleorderOrderList", saleorderOrderList);
            map.put("saleorderModelList", saleorderModelList);
            return AjaxResult.success(map);
        }
        saleorderOrder.setDeptId(companyId);
        saleorderOrderList = iSaleorderService.selectOrder(saleorderOrder);

        for (int i = 0; i < saleorderOrderList.size(); i++) {
            SaleorderOrder saleorderOrder1 = saleorderOrderList.get(i);
            saleorderModelList.addAll(saleorderOrder1.getSaleorderModels());
        }

        map.put("saleorderOrderList", saleorderOrderList);
        map.put("saleorderModelList", saleorderModelList);
        return AjaxResult.success(map);
    }

}
